using System.Text.Json.Nodes;
using AutoTest.Common.Extension;

namespace Jztech.Collector.Common.Extension
{
    /// <summary>
    /// JSON扩展方法
    /// </summary>
    public static class JsonExtension
    {
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="jsonObject"></param>
        /// <param name="pathData"></param>
        /// <param name="splitChar"></param>
        /// <returns></returns>
        public static JsonNode GetJsonPathValue(this JsonNode jsonObject, string pathData, string splitChar = ".",JsonNode parentJsonObject = null!)
        {
            if (jsonObject == null) return null!;
            if (pathData.IsEmpty()) return string.Empty;
            var splitIndex = pathData.IndexOf(splitChar);
            if (splitIndex < 0) return jsonObject[pathData]!;
            var segment = pathData[..splitIndex];
            var leaveSegment = pathData[(splitIndex + 1)..];
            JsonNode obj;
            if (string.Compare(segment, "$parent", true) == 0)
            {
                if (parentJsonObject == null) return "";

                splitIndex = leaveSegment.IndexOf(splitChar);
                if (splitIndex < 0) return parentJsonObject[leaveSegment]!;
                segment = leaveSegment[..splitIndex];
                leaveSegment = leaveSegment[(splitIndex + 1)..];
                obj = parentJsonObject[leaveSegment]!;
            }
            else
            {
                obj = jsonObject[segment]!;
            }
            
            if (leaveSegment.IsEmpty()) return obj;

            return obj.GetJsonPathValue(leaveSegment);
        }

        public static bool IsJsonArray(this JsonNode jsonObject) { return jsonObject is JsonArray; }

    }
}
